package com.xbn.netty.nettyGroupChat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author XBN
 * @date 2020/10/21 14:29
 * @email 78742541@qq.com
 */
/*
* netty实现群聊服务端
* */
public class GroupChatServer
{
    private  int port;//监听端口

    public GroupChatServer(int port) {
        this.port=port;
    }
    //编写一个run方法处理客户端请求
    public void run () throws InterruptedException {
        //首先创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGourp = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup,workerGourp)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //获取到pipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //该decoder作用是向pipeline里面加入一个解码器，
                            pipeline.addLast("decoder",new StringDecoder());
                            //加入一个编码器
                            pipeline.addLast("encoder",new StringEncoder());
                            //加入自定义handler,进行业务处理
                            pipeline.addLast(new GroupChatServerHandler());
                        }
                    });
            //关闭监听
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("服务端已经启动，绑定的端口是:"+port);
            //监听关闭
            //  主线程执行到这里就 wait 子线程结束，子线程才是真正监听和接受请求的，子线程就是Netty启动的监听端口的线程；
            //阻塞主线程,同步等待子线程的结果.如果不同步等待,会导致主线程一下子执行完毕.
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGourp.shutdownGracefully();
        }


    }
    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(7000).run();
    }
}
